import Message from '@/components/message'
import useStore from '@/store'
import axios, { AxiosError } from 'axios'

// 备用接口地址1: https://apipc-xiaotuxian-front.itheima.net/
// 备用接口地址2: http://pcapi-xiaotuxian-front.itheima.net/
// 备用接口地址3: http://pcapi-xiaotuxian-front-devtest.itheima.net/
export const baseURL = 'https://apipc-xiaotuxian-front.itheima.net/'
const instance = axios.create({
  // baseURL: 'https://apipc-xiaotuxian-front.itheima.net/',
  baseURL,
  timeout: 5000
})

// 添加请求拦截器
instance.interceptors.request.use(
  function (config) {
    const {user} = useStore()
    config.headers!.Authorization = `Bearer ${user.profile.token}`
    // 在发送请求之前做些什么
    return config
  },
  function (error) {
    // 对请求错误做些什么
    return Promise.reject(error)
  }
)

// 添加响应拦截器
instance.interceptors.response.use(
  function (response) {
    return response
  },
  function (error:AxiosError<{code:string,message:string}>) {
    if(!error.response){
      Message.error('网络错误,请稍后再试!')
    }else{
      const {code,message} = error.response.data
      if(code==='501' && message === '三方登录失败'){
        Message.success('QQ授权成功~')
      }else{
        Message.error(error.response.data.message)

      }
    }
    // 对响应错误做点什么
    return Promise.reject(error)
  }
)

export default instance